package auths

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/fizz-gorm2/global/consts"
	"gitee.com/youbeiwuhuan/gin-practice/fizz-gorm2/tools/render"
	"github.com/gin-gonic/gin"
)

type HeaderParams struct {
	Token string `header:"_token"`
}

func UserId() gin.HandlerFunc {
	return func(context *gin.Context) {
		token := context.GetHeader(consts.TOKEN)
		fmt.Printf("-------------token---%s \n", token)

		// 获取userId并设置
		context.Set(consts.USER_ID, "1234556")
		context.Next()

	}
}

// CheckTokenAuth 检查token有效性中间件
func CheckTokenAuth() gin.HandlerFunc {

	return func(context *gin.Context) {
		headerParams := HeaderParams{}

		//  推荐使用 ShouldBindHeader 方式获取头参数
		if err := context.ShouldBindHeader(&headerParams); err != nil {
			render.ReturnAuthFail(context)
			context.Abort()
			return
		}
		token := headerParams.Token
		tokenIsEffective := token != ""
		if tokenIsEffective {
			context.Next()
		} else {
			render.ReturnAuthFail(context)
			context.Abort()

		}

	}
}
